import React, { useEffect, useRef, useState } from 'react';
import { View } from '@tarojs/components';
import './countDown.scss';
import { formatNumber } from '../../../utils';
/*
*
*
* */
// 计算倒计时
export function countdownTime(time, mode) {
  let diff = time - new Date().getTime();
  if (!diff || diff < 0) {
    return;
  }
  let baseTime = 24 * 60 * 60 * 1000; // 天基数
  const day = Math.floor(diff / baseTime);
  diff = diff % baseTime;
  baseTime = baseTime / 24;
  let hour = Math.floor(diff / baseTime);
  diff = diff % baseTime;
  baseTime = baseTime / 60;
  const minute = Math.floor(diff / baseTime);
  diff = diff % baseTime;
  baseTime = baseTime / 60;
  const seconds = Math.floor(diff / baseTime);

  if (mode == 1) {
    hour += day * 24;

    return [hour, minute, seconds]
      .map(formatNumber)
      .join(':')
      .split('');
  }
  return `${day}天${hour}时${minute}分`;
}
function Index(props) {
  const [date, setDate] = useState([]);
  const refObj = useRef(null);
  const { time, extraTextFun } = props;

  useEffect(()=>{
    setDate(countdownTime(time, 1) || []);
    if (time) {
      refObj.current = setInterval(()=>{
        setDate(countdownTime(time, 1) || []);
      },1000);
    }
    return ()=>{
      clearInterval(refObj.current);
    }
  },[time]);

  return (
    <View className='countDown'>
      {
        date.map((i)=>{
          if (i === ':') {
            return <View className='fenGe'>:</View>
          } else {
            return <View className='number'>{i}</View>
          }
        })
      }
      {
        extraTextFun && extraTextFun(countdownTime(time, 1))
      }
    </View>
  );
}

export default Index;
